<template>
	<view class="content">
		<view class="search">
			<view class="search-box">
				<uni-icons type="search" size="16" color="#AAAAAA"></uni-icons>
				<input type="text" v-model="value" @input="clearInput" placeholder="请输入学生名称">
				<uni-icons type="close" size="20" color="#999" v-if="showClearIcon" @click="clearIcon"></uni-icons>
			</view>
			<button @click="secList()">搜索</button>
		</view>
		<view class="result-list">
			<view class="student-score" v-for="(item,index) in listData" @click="gotoPage(item)">
				<view class="student-top">
					<view class="top-l">
						<text :class="item.xs_sex==1?'ns-sex sex-box':'nan-sex sex-box'">{{item.number}}</text>
						<text>{{item.xs_name}}</text>
					</view>
					<text>{{item.bj_name}}</text>
				</view>
				<view class="score-list">
					<view :class="itemm.state?'score-fs score-jg':'score-fs score-bjg'" v-for="itemm in item.pros">
						<image :src="'/static/images/item'+itemm.id+'.png'" mode="widthFix"></image>
						<text>{{itemm.name}}</text>
					</view>
				</view>
			</view>
			<view v-if="noMore" class="no-more">
				<text>没有更多</text>
			</view>
			<!-- <view class="item-box" v-for="item in listData" @click="gotoPage(item)">
				<text style="width: 25%;">{{item.xs_name}}</text>
				<text style="width: 40%;">{{item.bj_name}}</text>
				<text style="width: 10%;">{{item.number}}</text>
				<text style="width: 25%;">{{item.state?'完成':'未完成'}}</text>
			</view> -->
		</view>
		<view class="fixed-btn">
			<button @click="endBtn">结束测试</button>
			<!-- <text>结束时间：2025/04/25 18:00</text> -->
		</view>
		
		<!-- 弹窗 -->
		<showModelVue ref="modelPopup" :textWord="'是否确认结束'" @bindChange='submitEnd'></showModelVue>
	</view>
</template>

<script>
	import showModelVue from '../../components/showModel.vue'
	export default {
		components:{showModelVue},
		data() {
			return {
				value:'',
				listData:[],
				pageNum:1,
				pageSize:10,
				noMore: false,
				dlId:'',
				typeData:[],
				pro:[],
				devices:[],
				endList:[],
				total:'',
				showClearIcon: false,
			}
		},
		onLoad(options) {
			this.dlId = options.id
			this.pro = options.pid.split(',')
			this.devices = options.devices.split(',')
			this.getPro()
			this.getUser()
		},
		onShow() {

		},
		onReachBottom() {
		    if (!this.noMore) {
		      this.pageNum++
		      this.getList(this.dlId)
		    }
		},
		methods: {
			async getUser(){
				let res = await this.http('get','/system/user/getInfo')
				console.log(res)
				if(res.code==200){
					this.getDevice(res.user.deptId)
				}
			},
			async getDevice(e){
				let data=[]
				let res = await this.http("get","/tc/shebei/list",{
					pageNum:1,
					pageSize:8,
					sbXxid:e,
					sbClientid:''
				})
				if(res.code==200){
					res.rows.forEach(item=>{
						this.devices.forEach(itemm=>{
							if(item.id==itemm){
								data.push({
									sbIp:item.sbIp2,
									projectid:item.shebeiProjectList[0].projectid
								})
							}
						})
					})
					this.endList = data
					// console.log(data)
				}
			},
			async getPro(){
				let res = await this.http("get","/tc/project/list",{pageNum:1,pageSize:100})
				if(res.code==200){
					this.typeData = res.rows
					this.getList(this.dlId)
				}
			},
			clearInput: function(event) {
				this.value = event.detail.value;
				if (event.detail.value.length > 0) {
					this.showClearIcon = true;
				} else {
					this.showClearIcon = false;
				}
			},
			clearIcon: function() {
				this.value = '';
				this.showClearIcon = false;
				this.pageNum = 1
				this.listData = []
				this.getList(this.dlId)
			},
			secList(){
				if(this.value==''){
					this.toast('请输入搜索内容')
					return false
				}else{
					this.pageNum = 1
					this.listData = []
					this.getList(this.dlId)
				}
			},
			async getList(e) {
				let that = this
				let res = await this.http("get","/tc/tcOperate/tcQueueStudentList",{
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					queueid: e,
					sname:this.value
				})
				console.log(res)
				if(res.code==200){
					let status = false
					res.rows.forEach(item=>{
						const obj = JSON.parse(item.pro);
						const entries = Object.entries(obj);
						console.log(entries)
						const result = entries.map(([key, state]) => ({
						  id: key.slice(3),
						  name: that.typeData.find(item=>item.id==parseInt(key.slice(3))).xmMc,
						  state
						}));
						console.log(result)
						item.pros=result
						const values = Object.values(JSON.parse(item.pro))
						item.state = checkAllTrue(values)
						function checkAllTrue(arr) {
						    for (let item of arr) {
						        if (!item) return false;
						    }
						    return true;
						}
					})
					this.total = res.total
					// this.listData = res.rows
					// 数据拼接处理
					 this.listData = [...this.listData, ...res.rows]
					// 判断是否还有数据
					 this.noMore = res.rows.length < 10
					 console.log(this.listData)
				}
			},
			endBtn(){
				this.$refs.modelPopup.openModel()
			},
			async submitEnd(){
				let that=this
				let res = await that.http("post","/tc/tcOperate/overTcqueue",{id:that.dlId})
				if(res.code==200){
					// that.toast(res.msg)
					uni.showLoading({
						title: '结束中'
					});
				}
				try {
					const requests = that.endList.map(item => new Promise((resolve, reject) =>{
						const sbIp = item.sbIp
						const result = sbIp.replace(/^(.*?):.*$/, (match, group1) => group1 || sbIp);
						const formData = { 
							ope: 'B',
							pid: item.projectid,
							nmn:that.total,
							qid:that.dlId
						  };
						console.log(result)
						uni.request({
							url: 'http://'+result+':8000', //仅为示例，并非真实接口地址。
							data: formData,
							timeout: 120000,
							sslVerify: false,
							header:{
								'content-type':'application/x-www-form-urlencoded'
							},
							method:'post',
							success: (res1) => {
								console.log(res1.data);
								resolve(res1.data.status)
							},
							fail: (err) => {
								console.error('请求失败:', err);
								reject(err); // 必须处理失败
							}
						});
					}))
					// 等待全部完成
					const responses = await Promise.all(requests);
					// 验证结果
					const allSuccess = responses.every(res2 => res2 == 'success');
					// console.log(requests)
					// console.log(responses)
					// console.log(allSuccess)
					if (allSuccess) {
					  this.toast('结束成功')
					  uni.hideLoading();
					  uni.switchTab({
						url:'/pages/index/index'
					  })
					}
				}catch (error) {
					// uni.showToast({ title: '部分请求失败', icon: 'error' });
					console.log('部分请求失败:',error)
					setTimeout(()=>{
						uni.hideLoading();
						uni.switchTab({
							url:'/pages/index/index'
						})
					},500)
				}
			},
			gotoPage(item){
				// console.log(item)
				const checkState = (arr) => {
				  return arr.some(itemm => itemm.state === true);
				};
				let isGo = checkState(item.pros)
				if(isGo){
					uni.navigateTo({
						url:'/pages/score/scoreDetails?id='+item.studentid+'&qId='+item.id+'&num='+item.number
					})
				}else{
					this.toast('未测试完成')
				}
			}
		}
	}
</script>

<style lang="less">
	.search{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20upx;
		.search-box{
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: calc(100% - 144upx);
			height: 56upx;
			border-radius: 86upx;
			background: #F5F7F9;
			padding: 0 20upx;
			box-sizing: border-box;
			input{
				width: 90%;
				font-size: 24upx;
				margin-left: 10upx;
			}
		}
		button{
			width: 124upx;
			height: 56upx;
			border-radius: 32upx;
			background: linear-gradient(180deg, #4F9FE0 0%, #3673E1 100%);
			font-size: 24upx;
			color: #fff;
			margin: 0;
		}
	}
	.fixed-btn{
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #fff;
		box-shadow: 0upx -8upx 20upx 0upx rgba(0, 0, 0, 0.1);
		padding: 20upx 40upx;
		box-sizing: border-box;
		button{
			border-radius: 120upx;
			background: linear-gradient(0deg, #5EA9FA 0%, #7CB6F5 100%);
			color: #fff;
		}
		text{
			display: block;
			text-align: center;
			color: #9E9E9E;
			font-size: 24upx;
			margin: 10upx 0;
		}
	}
	.result-list{
		width: 100%;
		padding-bottom: 190upx;
	}
	.student-score{
		width: 100%;
		margin-bottom: 20upx;
		border-radius: 8upx;
		background: #F0F7FA;
		padding: 20upx;
		box-sizing: border-box;
		.student-top{
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 20upx;
			.top-l{
				display: flex;
				align-items: center;
			}
			.sex-box{
				width: 40upx;
				height: 40upx;
				border-radius: 50%;
				display: block;
				margin-right: 10upx;
				text-align: center;
				line-height: 40upx;
				font-size: 24upx;
			}
			.ns-sex{
				background-color: #F9CBDE;
			}
			.nan-sex{
				background-color: #C4DCF6;
			}
			text{
				font-size: 28upx;
				color: #1a1a1a;
			}
		}
		.score-list{
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			.score-jg{
				background: linear-gradient(180deg, #93C3F7 0%, #54A0EF 100%);
			}
			.score-bjg{
				background: linear-gradient(180deg, #F7C393 0%, #EF7B54 100%);
			}
			.score-fs{
				margin: 0 1%;
				padding: 10upx 20upx;
				box-sizing: border-box;
				border-radius: 12upx;
				display: flex;
				align-items: center;
				image{
					width: 30upx;
					height: auto;
					filter: brightness(0%) invert(100%) !important;
					-webkit-filter: brightness(0%) invert(100%) !important;
					display: block;
					margin-right: 10upx;
				}
				text{
					font-size: 24upx;
					color: #fff;
				}
			}
		}
	}
</style>